# -*- coding: utf-8 -*-
__author__ = 'xuliliang'
# @Time    : 2018/10/9 下午2:20
# @Author  : 'xuliliang'
# @Email   : xuliliang@u51.com
# @File    : FtpApi.py
# @Software: PyCharm


# !/usr/bin/python
# coding=gbk
''''' 
    ftp自动下载、自动上传脚本，可以递归目录操作 
'''

from ftplib import FTP
import os, sys, string, datetime, time
import socket
from django.conf import  settings







class MYFTP(object):
	def __init__(self,host_list,username,password,remotedir):
		self.hostaddr = host_list
		self.username = username
		self.password = password
		self.remotedir = remotedir
		self.port = '21'
		self.ftp = FTP()
		# self.ftp.set_debuglevel(2)
	def __del__(self):
		self.ftp.close()

	def login(self):
		ftp = self.ftp
		try:
			timeout = 300
			socket.setdefaulttimeout(timeout)
			ftp.set_pasv(True)

			debug_print('开始连接到 %s' % (self.hostaddr))
			ftp.connect(self.hostaddr, self.port)
			debug_print('成功连接到 %s' % (self.hostaddr))
			debug_print('开始登录到 %s' % (self.hostaddr))
			ftp.login(self.username, self.password)
			debug_print('成功登录到 %s' % (self.hostaddr))
			debug_print(ftp.getwelcome())
		except Exception:
			debug_print("连接或登录失败")
		try:
			ftp.cwd(self.remotedir)
		except(Exception):
			debug_print('切换目录失败')


	def is_same_size(self, localfile, remotefile):
		try:
			remotefile_size = self.ftp.size(remotefile)
		except:
			remotefile_size = -1
		try:
			localfile_size = os.path.getsize(localfile)
		except:
			localfile_size = -1
		debug_print('lo:%d  re:%d' % (localfile_size, remotefile_size), )
		if remotefile_size == localfile_size:
			return 1
		else:
			return 0

	def upload_file(self, localfile, remotefile):
		if not os.path.isfile(localfile):
			return 10
		if self.is_same_size(localfile, remotefile):
			debug_print('跳过相等的文件: %s' % localfile)
			return  20

		try:
			file_handler = open(localfile, 'rb')
			self.ftp.storbinary('STOR %s' % remotefile, file_handler)
			debug_print('上传: %s' % localfile + " 成功!" )
			file_handler.close()
			return 30
		except:
			debug_print('3939393939')
			return 40

	def upload_files(self, localdir='./', remotedir='./'):
		try:
			if not os.path.isdir(localdir):
				debug_print('本地目录 %s 不存在' % localdir)
				return
			localnames = os.listdir(localdir)
			self.ftp.cwd(remotedir)
			debug_print('切换至远程目录: %s' % self.ftp.pwd())
			for item in localnames:
				src = os.path.join(localdir, item)
				debug_print("本地文件路径============>>>>>>>>>>>>>>>>>>%s"%src)
				if os.path.isdir(src):
					try:
						self.ftp.mkd(item)
					except:
						debug_print('目录已存在 %s' % item)
					self.upload_files(src, item)
					# print self.ftp.pwd()
				else:
					self.upload_file(src, item)
			self.ftp.cwd('..')
			return True
		except:
			return False

	def ftp_path_check(self,path):
		try:
			self.ftp.cwd(path)
			debug_print(self.ftp.pwd())
			return True
		except:
			return  False
	def files_list(self,dir):
		try:
			debug_print(self.ftp.nlst(dir))
			return True
		except:
			return False




#########################################################
#配置
# host_list = '10.1.126.10'  # ftp地址
hostaddr = '10.247.22.146'  # ftp地址
username = 'zhongpminghua'  # 用户名
password = '021dc9898ae4447a0d3bd4da0b83a439'  # 密码
port = 21  # 端口号
rootdir_remote = './bdplatform/mgmt/apk/'



def debug_print(s):
	print ('\033[1;35m %s \n  \033' % s)



def upload_file_to(local_file,remote_file):
	if len(host_list) >=1 :
		f = MYFTP(host_list[0], username, password, rootdir_remote)
		f.login()
		res = f.upload_file(local_file,rootdir_remote+remote_file)

		f1 = MYFTP(host_list[1], username, password, rootdir_remote)
		f1.login()
		res1 = f1.upload_file(local_file, rootdir_remote + remote_file)
		if res == res1 and res == 30:
			return True
		elif res == res1 and res == 20:
			return True
		else:
			return  False


def upload_files_to(local_path,remote_path):
	if len(host_list) >=1 :
		f = MYFTP(host_list[0], username, password, rootdir_remote)
		f.login()
		res = f.upload_files(local_path,rootdir_remote+remote_path)

		f1 = MYFTP(host_list[1], username, password, rootdir_remote)
		f1.login()
		res1 = f1.upload_files(local_path, rootdir_remote + remote_path)

		if res == res1 and res == True:
			return True
		else:
			return False

# f = MYFTP(hostaddr, username, password, rootdir_remote)
# f.login()
# f.upload_file('/Users/u51/Documents/20160712110935064.png', '20160712110935064.png')
# f.files_list('./')
# print("iok")
#
# upload_file_to('/Users/u51/Documents/20160712110935064.png','./20160712110935064.png');
# upload_file_to('/Users/u51/Documents/timg.jpeg','./timg.jpeg');


# upload_files_to('/Users/u51/Documents/django/auto_op/DevOps/adminset','./');
# upload_files_to('/Users/u51/Documents/django/auto_op/DevOps/adminset','./');

